﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using WebApplication.Models;

namespace WebApplication.Controllers
{
    public class GameController : Controller
    {
        //
        // GET: /Game/
        Gamesrv.ServerImplClient client;
        


        public GameController()
        {
             client = new Gamesrv.ServerImplClient();             
             var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                 @"d:\Programs\Java\glassfish3\glassfish\domains\domain1\s1as.cer");
             client.ClientCredentials.ClientCertificate.Certificate = cert;                          
        }

        int Handle
        {
            get {
             var handleObj = Session != null ? Session["handle"]:null;
             if (handleObj == null)
                 return  -1;
             else
                 return  (int)handleObj;   
            }
            set {
                 Session["handle"] = value;
            }
        }


        public ActionResult Start()
        {
            
            var gameTypes = client.getGameTypes();

            ViewBag.GameType = new SelectList(gameTypes);

            return View("Start",gameTypes);
        }

        [HttpPost]
        public ActionResult Start(string username, string type)
        {            
            var model = new GameModel();
            Handle = client.startGame(type, username);
            
            model.Nickname = username;
            model.Type = type;            
            model.Situation = new[]{
                new []{ " "," "," "},
                new []{ " "," "," "},
                new []{ " "," "," "},
            };
            StatusChangedEvent.Set();            
            return   View("Game",model);
        }


        static ManualResetEvent StatusChangedEvent = new ManualResetEvent(false);
        public bool WaitForMove(string status)
        {
            
            var srverstatus = client.getGameStatus(Handle).ToString();
            if (srverstatus != status)
                return true;
            return false;
            StatusChangedEvent.Reset();
            StatusChangedEvent.WaitOne(1000);
            srverstatus = client.getGameStatus(Handle).ToString();
            return srverstatus != status;            
        }


        [HttpPost]
        public ActionResult Game(GameModel model,int? move_row, int? move_col)
        {            

            if (move_row != null) {
                client.makeMove(Handle, move_row.Value.ToString() + move_col.Value.ToString());
                StatusChangedEvent.Set();
                
            }

            var status = client.getGameStatus(Handle);
            model.Status =
                  status == Gamesrv.gameStatus.WaitingForMove ? GameStatus.WaitingForMove
                : status == Gamesrv.gameStatus.WaitingForOtherPlayers ? GameStatus.WaitingForOtherPlayers
                : status == Gamesrv.gameStatus.ReadyForMove ? GameStatus.ReadyForMove
                : status == Gamesrv.gameStatus.Finished ? GameStatus.Finished
                : 0;
            
            model.Situation = new[]{
                new []{ " "," "," "},
                new []{ " "," "," "},
                new []{ " "," "," "},
            };

            if (model.Status != GameStatus.WaitingForOtherPlayers && string.IsNullOrEmpty(model.OponentNickname)) {
                model.MyNumber = client.getMyNumber(Handle);
                model.OponentNickname = client.getUserName(Handle, 1 - model.MyNumber);

                var serverSit = client.getSituation(Handle);
                for (int r = 0; r < 3; r++)
                    for (int c = 0; c < 3; c++)
                        model.Situation[r][c] = serverSit[r].item[c];            
            
            }

            

            
            
            return View(model);
        }
    }
}
